/* Copyright 2009 CtrlSpace Platform
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * 		http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * Contributor(s):
 *		Marc Obaldo (marcklaser@gmail.com)
 */

dojo.provide("ctrlspace.IDE");
dojo.require("ctrlspace.ui.UI");
dojo.declare("ctrlspace.IDE", null, {
	// Attributes
	// Constructor
	constructor: function(user) {
		this.UI = {};
		this._initialize(user);
		this._pluginRegistry = {};
		this.user = user;
//		this.user = dojo.toJSON(user);
	},

	// Public methods
	getPlugin: function(pluginId) {
		return this._pluginRegistry[pluginId];
	},
	
	getUI: function() {
		return this.UI;
	},

	// Private methods
	_initialize: function(user) {
		if (user.isLogged != null) {
			this.UI = new ctrlspace.ui.UI();
			this._loadPlugins();
		}
	},
	
	_loadPlugins: function() {
		var load = dojo.xhrGet({
			url: "mock/plugins.json?" + djConfig.cacheBust,
			handleAs: "json"
		});
		
		load.addCallback(dojo.hitch(this, this._pluginListLoaded));
	},
	
	_getPlugin: function(pluginName, properties) {
		var args = Array.prototype.slice.call(arguments).splice(2);
		var namespaces = pluginName.split(".");
		var func = namespaces.pop();
		var context = window;
		for(var i = 0; i < namespaces.length; i++) {
			context = context[namespaces[i]];
		}

		return new context[func](properties);;
	},

	_pluginListLoaded: function(data) {
		// Iterate through plugins
		for (var i in data.plugins) {
			// Get plugin ID and require JS
			var plugin = data.plugins[i];
			var pluginId = plugin.id;

			// Create array of plugins
			var pluginInstances = [];

			// OR instantiate each copy of extension
			for (var ext in plugin.extensions) {
				dojo['require'](plugin.extensions[ext]);
				var pluginInstance = this._getPlugin(plugin.extensions[ext], plugin).plugin;
				
				if (pluginInstance != null) {
					pluginInstances.push(pluginInstance);
				}
			}
			
			// Add plugin instances to registry
			if (pluginInstances.length > 0) {
				// Register plugin instance
				this._pluginRegistry[pluginId] = pluginInstances;
			}
		}
	}
});